#include <stdlib.h>
#include <stdbool.h>
#include <stdio.h>
#define MAXSIZE 5

typedef int Position;
typedef struct QNode *PtrToQNode;
struct QNode
{
    double *data;
    Position Front, Rear;
    int MaxSize;
};
typedef PtrToQNode Queue;

Queue CreateQueue(int);
bool IsFull(Queue);
bool InsertQ(Queue, double);
bool IsEmpty(Queue);
double DeleteQ(Queue);
void DisplayQ(Queue);

int main()
{
    double num_for_insert;
    Queue Q = CreateQueue(MAXSIZE);

    for (int i = 0; i < 5; i++)
    {
        scanf("%lf", &num_for_insert);
        if(InsertQ(Q, num_for_insert))
            printf("Insert Success !\n");
    }
    DisplayQ(Q);

    DeleteQ(Q);
    DeleteQ(Q);
    DisplayQ(Q);

    InsertQ(Q, 10.0);
    InsertQ(Q, 100.0);
    DisplayQ(Q);

    return 0;
}

Queue CreateQueue(int MaxSize)
{
    Queue Q = (Queue)malloc(sizeof(struct QNode));
    Q->data = (double *)malloc(MaxSize * sizeof(double));
    Q->Front = Q->Rear = 0;
    Q->MaxSize = MaxSize;
    return Q;
}

bool IsFull(Queue Q)
{
    return ((Q->Rear + 1) % Q->MaxSize == Q->Front);
}

bool InsertQ(Queue Q, double X)
{
    if(IsFull(Q)) {
        printf("Queue is full !\n");
        return false;
    } else {
        Q->Rear = (Q->Rear + 1) % Q->MaxSize;   //当队列为空时，下标为0的位置上没有数据
        Q->data[Q->Rear] = X;                   
        return true;
    }
}

bool IsEmpty(Queue Q)
{
    return (Q->Front == Q->Rear);
}

double DeleteQ(Queue Q)
{
    if(IsEmpty(Q))
    {
        printf("Queue is empty !\n");
        return 0;
    }   else
    {
        Q->Front = (Q->Front + 1) % Q->MaxSize;
        return Q->data[Q->Front];
    }
}

void DisplayQ(Queue Q)
{
    if(Q->Front <= Q->Rear)
    {
        for (int i = Q->Front + 1; i < Q->Rear + 1; i++)
            printf("%lf ", Q->data[i]);
        printf("\n");
    }   else
    {
        for (int i = Q->Front + 1; i < Q->Rear + MAXSIZE + 1; i++)
            printf("%lf ", Q->data[i % MAXSIZE]);
        printf("\n");
    }

    printf("Q->Front = %d\n", Q->Front);
    printf("Q->Rear = %d\n", Q->Rear);
    printf("\n");
}